package cloud.keveri.chat4j.provider.chatgpt.listener;

import cloud.keveri.chat4j.api.entity.chat.Message;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;

/**
 * 借鉴自  <a href="https://gitee.com/grt1228/chatgpt-java">chatgpt-java<a/>
 * <p>
 * 作者：沈自在
 **/
@Slf4j
@RequiredArgsConstructor
public class DefaultChatgptEventSourceListener extends AbstractChatgptEventSourceListenerAdapter {

    /**
     *
     */
    private final ResponseBodyEmitter emitter;

    /**
     * on Message
     */
    @Override
    protected void onMessage(Message delta) {
        try {
            emitter.send(delta.getContent());
        } catch (IOException e) {
            log.error("[Chat4j] An error occurred while streaming a reply back message");
        }
    }

    @Override
    protected void onComplete() {
        emitter.complete();
    }
}
